package org.nanyuan.forum.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.nanyuan.forum.Utils.MD5Util;
import org.nanyuan.forum.Utils.StringUtil;
import org.nanyuan.forum.Utils.UUIDUtil;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.config.AppConfig;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IUserService;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
//路由映射，一级路径
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @PostMapping("/register")
    public AppResult register(@RequestParam("username") @NonNull String username,
                              @RequestParam("nickname") @NonNull String nickname,
                              @RequestParam("password") @NonNull String password,
                              @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
//        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(nickname)
//        || !StringUtils.hasLength(password) || !StringUtils.hasLength(passwordRepeat)) {
//
//            //返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        //校验两次密码是否一样
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成随机盐值
        String salt = UUIDUtil.UUID_32();
        //2.生成密码的密文
        String encryptPassword = MD5Util.md5Salt(password, salt);
        //3.设置密码和盐值
        user.setSalt(salt);
        user.setPassword(encryptPassword);
        // 调用Service
        userService.createNormalUser(user);

        //返回成功
        return AppResult.success("注册成功");
    }

    @PostMapping("/login")
    public AppResult login(@RequestParam("username") @NonNull String username,
                           @RequestParam("password") @NonNull String password,
                           HttpServletRequest request) {
        //调用service层的login方法，返回user对象
        User user = userService.login(username, password);
        //非空校验
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //登录成功，将user对象设置到session当中
        HttpSession session = request.getSession();
        session.setAttribute(AppConfig.USER_SESSION, user);

        //返回结果
        return AppResult.success("登录成功");
    }

    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id) {

        //定义返回的user对象
        User user = null;
        //根据id是否为空，判断user对象的获取方法
        if (id == null) {
            //1.id为空，从session中获取用户信息
            HttpSession session = request.getSession(false);
            //从session中获取当前对象
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            //2.id不为空，从数据库中查询用户信息
            user = userService.selectById(id);
        }
        //判断用户对象是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //返回正确的结果
        return AppResult.success(user);
    }

    /**
     * 退出登录
     *
     * @param request 请求
     * @return AppResult
     */
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session对象
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if (session != null) {
            //打印日志
            log.info("退出成功");
            //表示用户的登录状态，直接销毁session
            session.invalidate();
        }

        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param gender   性别
     * @param email    邮箱
     * @param phoneNum 电话
     * @param remark   个人简介
     * @return AppResult
     */
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @RequestParam(value = "username", required = false) String username,
                                @RequestParam(value = "nickname", required = false) String nickname,
                                @RequestParam(value = "gender", required = false) Byte gender,
                                @RequestParam(value = "email", required = false) String email,
                                @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @RequestParam(value = "remark", required = false) String remark) {
        //1.非空校验
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {

            //返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        //从session中获取用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());  //用户id
        updateUser.setUsername(username); //用户名
        updateUser.setNickname(nickname); //昵称
        updateUser.setGender(gender); //性别
        updateUser.setEmail(email); //邮箱
        updateUser.setPhoneNum(phoneNum); //电话
        updateUser.setRemark(remark); //个人简介
        //3.调用service
        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user = userService.selectById(user.getId());
        //更新session
        session.setAttribute(AppConfig.USER_SESSION, user);
        //4.返回结果
        return AppResult.success(user);
    }

    /**
     * 修改密码
     * @param request   获取用户信息
     * @param oldPassword  老密码
     * @param newPassword   新密码
     * @param passwordRepeat  确认密码
     * @return AppResult
     */
    @PostMapping("/modifyPassword")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前登录用户的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁session
        if (session != null) {
            session.invalidate();
        }
        //返回结果
        return AppResult.success();
    }
}
